package org.hylexus.hadoop.hadoop_2_test.mr.demo2;

import java.io.IOException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

public class DataCount {
	public static void main(String[] args) throws Exception {

		Job job = Job.getInstance(new Configuration());
		job.setJarByClass(DataCount.class);

		job.setMapperClass(DataCount.DataMapper.class);
		job.setMapOutputKeyClass(Text.class);
		job.setMapOutputValueClass(DataBean.class);

		FileInputFormat.setInputPaths(job, new String("/dc-in.dat"));

		job.setReducerClass(DataCount.DataReducer.class);
		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(DataBean.class);

		FileOutputFormat.setOutputPath(job, new Path("/dc-out"));
		
		job.waitForCompletion(true);
	}

	public static class DataMapper extends Mapper<LongWritable, Text, Text, DataBean> {

		@Override
		protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, Text, DataBean>.Context context)
				throws IOException, InterruptedException {
			String line = value.toString();
			String[] words = line.split("\t");
			DataBean b = new DataBean(words[1], Long.parseLong(words[8]), Long.parseLong(words[9]));
			context.write(new Text(b.getPhone()), b);
		}
	}

	public static class DataReducer extends Reducer<Text, DataBean, Text, DataBean> {

		@Override
		protected void reduce(Text key, Iterable<DataBean> value,
				Reducer<Text, DataBean, Text, DataBean>.Context context) throws IOException, InterruptedException {
			if (value == null)
				return;
			long up = 0, down = 0;
			for (DataBean b : value) {
				up += b.getUp();
				down += b.getDown();
			}
			DataBean bean = new DataBean(key.toString(), up, down);
			context.write(key, bean);
		}

	}
}
